package it.agm.fanta.activity;


import it.agm.activity.dialog.GenericDialog;
import it.agm.fanta.FantaserviceApp;
import it.agm.fanta.R;
import it.agm.fanta.adapter.LegaSnippetAdapter;
import it.agm.fanta.adapter.NavDrawerAdapter;
import it.agm.fanta.adapter.TypeSnippetAdapter;
import it.agm.fanta.asynctask.jersey.patch.Callback;
import it.agm.fanta.asynctask.jersey.patch.NetworkHandler;
import it.agm.fanta.asynctask.util.SyncUtility;
import it.agm.fanta.constants.Constants;
import it.agm.fanta.exception.ConnectionException;
import it.agm.fanta.fragment.FragmentSessionFactory;
import it.agm.fanta.fragment.LoaderFragment;
import it.agm.fanta.model.GiocatorePartitaLega;
import it.agm.fanta.model.LegaSquadra;
import it.agm.fanta.model.NavItem;
import it.agm.fanta.model.Partita;
import it.agm.fanta.model.Partite;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.purplebrain.adbuddiz.sdk.AdBuddiz;
//import android.app.FragmentManager;


/**
 * Activity di accesso all'App. L'intera applicazione ?? districata in fragment richiamati da questa
 * Activity
 */
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
	private static final String S_HAS_PERMANENT_MENU_KEY = "sHasPermanentMenuKey";
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private Spinner mModuloSnipper;
	private ActionBarDrawerToggle mDrawerToggle;
	private Intent intent ;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navTitles; 
	private ActionBar actionBar;
	public Dialog mdialog;
	public String oldItem;
	private InterstitialAd interstitial;
	private String menuItem;
	private int menuItemPosition;
	
	/**
	 * Metodo che si occupa di creare la action
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		FantaserviceApp.setCurrentActivity(this);
		this.actionBar = getActionBar();
		this.mTitle = mDrawerTitle = mTitle;
		new GenericDialog(this,getResources().getString(R.string.alert_fantasercice),"INFO");
		
		managePublicity();
		manageNavigationDrower(R.array.navig_array);
		manageDropDownNavigation();
		try {
			//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
			Fragment fragment = FragmentSessionFactory.getFragmentById("");
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}


	/**
	 * 
	 */
	private void manageNavigationDrower(int idArray) {
		this.navTitles = getResources().getStringArray(idArray);
		this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		
		this.mDrawerList = (ListView) findViewById(R.id.left_drawer);
		getOverflowMenu();//Necessario per visualizzare le option nella actioBar con icona
		this.mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
		this.mDrawerList.setBackgroundColor(getResources().getColor(R.color.black_overlay));
		this.mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		if(this.mModuloSnipper == null){
			this.mModuloSnipper = new Spinner(this);
			menageSnipper();
			this.mDrawerList.addHeaderView(mModuloSnipper);
		}
		ArrayList<NavItem> navItems = new ArrayList<NavItem>();
		for(int i=0 ; i<this.navTitles.length ; i++){
			NavItem item = new NavItem();
			item.setText(this.navTitles[i]);
			String image =this.navTitles[i];
			image = image.replaceAll(" ","_");
			
			Drawable drawable = getResources().getDrawable(getResources().getIdentifier("action_"+image.toLowerCase(), "drawable", getPackageName()));
			item.setImage(drawable);
			navItems.add(item);
		}
		NavDrawerAdapter adapter = new NavDrawerAdapter(this, R.layout.activity_main,navItems);

		this.mDrawerList.setAdapter(adapter);
		actionBar.setDisplayHomeAsUpEnabled(true);
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
				mDrawerLayout, /* DrawerLayout object */
				R.drawable.v2_ic_drawer ,/* nav drawer image to replace 'Up' caret */
				R.string.drawer_open, /* "open drawer" description for accessibility */
				R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
//				getActionBar().setTitle(mTitle);
				selectItemByItemText(menuItem,menuItemPosition);
//				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
//				getActionBar().setTitle(mDrawerTitle);
//				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
	}


	/**
	 * 
	 */
	private void menageSnipper() {
		if(FantaserviceApp.leghe != null && FantaserviceApp.leghe.size()>0){
			LegaSnippetAdapter adapterLega = new LegaSnippetAdapter(this, R.layout.drawer_snippet_item,FantaserviceApp.leghe);	
			mModuloSnipper.setAdapter(adapterLega);
			mModuloSnipper.setOnItemSelectedListener(
	                new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
								LegaSquadra lega = FantaserviceApp.leghe.get(position);
								FantaserviceApp.request.setIdlega("" + lega.getIdlega());
								FantaserviceApp.request.setGiornataincorso(false);
								FantaserviceApp.lega = lega;
								
								SyncUtility.syncForLega(FantaserviceApp.getAppContext());
						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							// TODO Auto-generated method stub
							
						}
	                });
			mModuloSnipper.setSelection(0);
		}
	}


	/**
	 * 
	 */
	private void managePublicity() {
		// ADVIEW
		AdView adView = (AdView) this.findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		if (adView != null) {
			adView.loadAd(adRequest);
		}
		// ADVIEW
		// AdBuddiz START
		AdBuddiz.setPublisherKey(Constants.ADBUDDIZ_KEY);

		AdBuddiz.cacheAds(this); // this = current Activity
		// AdBuddiz end
		 // Create the interstitial. 
		interstitial = new InterstitialAd(MainActivity.this);
	    interstitial.setAdUnitId("ca-app-pub-6490192218888076/3583199997"); 
//	    AdRequest adr = new AdRequest.Builder().build();
//	    adr.addTestDevice("3568B71F11D9B0159B087FF911D4795A") ;
	 // Load ads into Interstitial Ads
        interstitial.loadAd(adRequest);
	    // Create ad request. 
//	    AdRequest adRequestInter = new AdRequest.Builder().build();
	 
        // Prepare an Interstitial Ad Listener
        interstitial.setAdListener(new AdListener() {
            public void onAdLoaded() {
                // Call displayInterstitial() function
                displayInterstitial();
            }
        });
	    
	    // Begin loading your interstitial. 
//	    interstitial.loadAd(adRequestInter);

	}
	
	public void displayInterstitial() {
        // If Ads are loaded, show Interstitial else show nothing.
        if (interstitial.isLoaded()) {
            interstitial.show();
        }
    }


	/**
	 * 
	 */
	private void manageDropDownNavigation() {
		//DropDown navigation Start
		this.actionBar.setDisplayShowTitleEnabled(false);
		this.actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		// Specify a SpinnerAdapter to populate the dropdown list. 
		final String[] dropdownValues = getResources().getStringArray(R.array.dropdown);
		ArrayList<String> typeList = new ArrayList<String>();
		for (int i = 0; i < dropdownValues.length; i++) {
			typeList.add(dropdownValues[i]);
		}
		
		
		TypeSnippetAdapter adapterLega = new TypeSnippetAdapter(this, R.layout.drawer_snippet_item,typeList);	
		//mModuloSnipper.setAdapter(adapterLega);
//	    ArrayAdapter<String> adapterDropDown = new ArrayAdapter<String>(actionBar.getThemedContext(),
//        android.R.layout.simple_spinner_dropdown_item, android.R.id.text1, dropdownValues);
	    // Set up the dropdown list navigation in the action bar. 
	    actionBar.setListNavigationCallbacks(adapterLega, this);
	  //DropDown navigation End
	}

	
	@Override
	protected void onResume() {
		
		selectItemByItemText(menuItem,0);
		invalidateOptionsMenu();
		
	    super.onResume();
	}
	/**
	 * Metodo che gestisce la creazione del menu di options
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	/**
	 * Metodo che gestisce le menu options
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}
	
	/**
	 * Metodo Necessario per visualizzare le option nella actioBar con icona
	 */
	private void getOverflowMenu() {

	    try {
	       ViewConfiguration config = ViewConfiguration.get(this);
	       Field menuKeyField = ViewConfiguration.class.getDeclaredField(S_HAS_PERMANENT_MENU_KEY);
	       if(menuKeyField != null) {
	           menuKeyField.setAccessible(true);
	           menuKeyField.setBoolean(config, false);
	       }
	   } catch (Exception e) {
	       e.printStackTrace();
	   }
	 }
	
	/**
	 * Metodo che gestisce lo switch tra le option del menu dell'actionBar
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {
		case R.id.action_logout:
			FantaserviceApp.utente = null;
			getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit()
	        .putString(Constants.PREF_USERNAME, null)
	        .putString(Constants.PREF_PASSWORD, null).commit();
			intent = new Intent(this,LoginActivity.class);
			startActivity(intent);
			finish();
			return true;
		case R.id.action_sync:
//			MenuItem refreshMenuItem = item;
			SyncUtility.syncForLega(this);
			//TODO chiamare gli async Task necessari alla sincronizzazione
			return true;
		case R.id.action_info:
			String versionName;
			try {
				versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
				new GenericDialog(FantaserviceApp.currentActivity(),"FantaService UnOfficial"+"\n v."+ versionName + "\nCreated by AGM\n" ,"Info");
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			return true;	
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 *  The click listner for ListView in the navigation drawer
	 */
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
	
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			TableRow layout = (TableRow)view;
			TextView textView = (TextView) layout.findViewById(R.id.textItem);
			menuItem = "" +textView.getText();
			menuItemPosition = position;
			if(getResources().getText(R.string.action_live).equals(menuItem)){
				FantaserviceApp.request.setCoppa(false);
				populateNCallLive();
				menuItem = oldItem;
			}else if(getResources().getText(R.string.action_live_coppa).equals(menuItem)){
				FantaserviceApp.request.setCoppa(true);
				populateNCallLive();
				menuItem = oldItem;
			}else if(getResources().getText(R.string.action_probabili_formazioni).equals(menuItem)){
				PackageManager pm = getPackageManager();
				Intent intent = pm.getLaunchIntentForPackage("it.agm.profor");
				if(intent != null){
					startActivity(intent);
				}else{
					final String appPackageName = "it.agm.profor"; // getPackageName() from Context or Activity object
					try { 
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
					} catch (android.content.ActivityNotFoundException anfe) {
					    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
					} 
				}
			}else{
				Fragment fragment = new LoaderFragment();
				FragmentManager fragmentManager = getSupportFragmentManager();
				oldItem = menuItem;
				fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
			}
			mDrawerLayout.closeDrawer(mDrawerList);
//			selectItemByItemText("" +textView.getText(),position);
		}
	}

	/**
	 * Metodo che gestisce lo switch tra le voci di menu della NavigationDrawer
	 * @param position
	 */
	private void selectItemByItemText(String textView,int position) {
		// update the main content by replacing fragments
		Fragment fragment;
		try {
			if(FantaserviceApp.lega == null && (!"".equals(textView) || textView == null)){
//				SyncUtility.syncForLega();
			}else{
				mDrawerList.setItemChecked(position, true);
				mDrawerTitle = textView;
//				actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);	
				if(getResources().getText(R.string.action_live).equals(textView)){
					populateNCallLive();
					textView = oldItem;
				}else{
					fragment = FragmentSessionFactory.getFragmentById(textView);
					FragmentManager fragmentManager = getSupportFragmentManager();
					oldItem = textView;
					fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
				}
			}
		} catch (ConnectionException e) {
			 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this,R.style.DialogTheme);
				
			 alertDialogBuilder.setTitle("ERROR");
			 alertDialogBuilder.setMessage(e.getMessage());
			 alertDialogBuilder.setNegativeButton("Chiudi",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					}
				});
			 AlertDialog alertDialog = alertDialogBuilder.create();
			 // show alert
			 alertDialog.show();
		}
				
	}

	/**
	 * 
	 */
	public void populateNCallLive() {
		NetworkHandler networkHandler = NetworkHandler.getInstance();
		
		String url = Constants.URL_REST ;
		if(FantaserviceApp.request.isCoppa()){
			url +=  Constants.SERVICE_GIORNATA_COPPA_LEGA;
		}else{
			url += Constants.SERVICE_GIORNATA_LEGA;
		}
				
		FantaserviceApp.request.setGiornataincorso(true);	
		Partite[] partiteTmp = null;
		if(SyncUtility.isConnectionPresent(this)){
		networkHandler.write(url, Partite[].class, partiteTmp,
				new Callback<Partite[]>() {
					@Override
					public void callback(Partite partite[]) {
						Partite partiteToAnalize = null;
						if(FantaserviceApp.request.isCoppa()){
							partiteToAnalize =  partite[0];
						}else{
							partiteToAnalize = partite[0];
						}
						for (Partita partiteLega : partiteToAnalize.getPartite()) {
							if (partiteLega.getSquadracasa().equals(FantaserviceApp.lega.getNomesquadra())
									|| partiteLega.getSquadratrasferta().equals(FantaserviceApp.lega.getNomesquadra())) {
								FantaserviceApp.request.setIdpartitalega(""+ partiteLega.getIdpartitalega());
								FantaserviceApp.partiteLegaCorrente = partiteLega;
								GiocatorePartitaLega[] giocatoriPartita = null;
								String url = Constants.URL_REST + Constants.SERVICE_PARTITA_LEGA;
								NetworkHandler networkHandler = NetworkHandler .getInstance();
								networkHandler.write(url,
												GiocatorePartitaLega[].class,
												giocatoriPartita,
												new Callback<GiocatorePartitaLega[]>() {
													@Override
													public void callback( GiocatorePartitaLega giocatoriPartita[]) {
														FantaserviceApp.request.setGiornataincorso(false);	
														ArrayList<GiocatorePartitaLega> list = new ArrayList<GiocatorePartitaLega>(Arrays.asList(giocatoriPartita));
														FantaserviceApp.giocatorePartitaLega = list;
														Intent intent = new Intent(FantaserviceApp.currentActivity(), PartitaPagerActivity.class);
														startActivity(intent);
													}
												});
								break;
							}
							
						}
					}
				});
		}else{
			new GenericDialog(FantaserviceApp.currentActivity(), SyncUtility.ERRORE_DI_CONNESSIONE,"ERROR");
		}
	}


	@Override
	public void setTitle(CharSequence title) {
		mTitle = title ;
		getActionBar().setTitle(mTitle );
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	  @Override 
	  public boolean onNavigationItemSelected(int position, long id) {
		switch (position) {
		case 0:
			manageNavigationDrower(R.array.navig_array);
			SyncUtility.syncInfoLega(NetworkHandler.getInstance());
			break;
		case 1:
			manageNavigationDrower(R.array.navig_coppa_array);
			SyncUtility.syncInfoCoppa(NetworkHandler.getInstance());
			break;
		default:
			manageNavigationDrower(R.array.navig_array);
			SyncUtility.syncInfoLega(NetworkHandler.getInstance());
			break;
		}
	   
	    return true; 
	  } 
}